package com.lucher.tangstore.controller;

import com.lucher.tangstore.common.Tools;
import com.lucher.tangstore.dao.MenuMapper;
import com.lucher.tangstore.dao.OperatorMapper;
import com.lucher.tangstore.dao.OperatorrolerefMapper;
import com.lucher.tangstore.dao.RoleMapper;
import com.lucher.tangstore.po.*;
import com.lucher.tangstore.service.IOperatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/operator")
public class OperatorController extends BaseController{
	@Resource  
    private IOperatorService operatorService; 
	@Autowired
	private OperatorrolerefMapper operatorrolerefDao;
	@Autowired
	private MenuMapper menuDao;
	@Autowired
	private RoleMapper roleDao;
	@Resource  
    private OperatorMapper operatorDao;

	@Autowired
	private OperatorrolerefMapper operatorroleref;

	

	/**
   	 * 进入用户登录界面
   	 * @throws Exception 
   	 */
    @RequestMapping("/login") 
    public String login(Operator form){
        return "operator/login"; 
    }
	
    /**
	 * 验证用户登录账号
	 * @throws Exception 
	 */
	@ResponseBody
	// 此标志就是返回json数据给页面的标志
	@RequestMapping(value = "/goLogin")
	public Map<String, Object> goLogin(Operator form, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 封装返回给页面的json对象
		HashMap<String, Object> responseJson = new HashMap<String, Object>();
		responseJson.put("code", "0");
		String Operatorname = request.getParameter("Operatorname");
		String password = request.getParameter("password");
		
		if(!"admin".equals(Operatorname)){
			responseJson.put("flag", "loginname_error");
			responseJson.put("error", "登录账号不正确");
			return responseJson;
		}else if(!"123456".equals(password)){
			responseJson.put("flag", "password_error");
			responseJson.put("error", "登录密码不正确");
			return responseJson;
		}
		
		// 保存操作员到session中
		//session.setAttribute("Operator", operator);
		responseJson.put("flag", "0");
		responseJson.put("error", "登录成功");
		return responseJson;
//		
//		Operator operator = operatorDao.findByLoginname(form);
//		if (operator != null) {
//			if (!"1".equals(operator.getStatus())) {
//				responseJson.put("flag", "loginname_error");
//				responseJson.put("error", "无效的操作员");
//				return responseJson;
//			} else if (!operator.getPassword().equals(passwordEncrypt)) {
//				responseJson.put("flag", "password_error");
//				responseJson.put("error", "登录密码不正确");
//				return responseJson;
//			}
//			// 保存操作员到session中
//			session.setAttribute("Operator", operator);
//
//			// 判断是否单点登录（不允许同一个操作员登录同时在俩个客户端在线）
//			String single_login = ConfigUtil.getConfigFilePath("single_login", "system.properties");
//			if (single_login.equals("1")) {
//				SessionListener.isLogined(session, form.getLoginname());
//			}
//			responseJson.put("flag", "0");
//			return responseJson;
//		} else {
//			responseJson.put("flag", "loginname_error");
//			responseJson.put("error", "登录账号不正确");
//			return responseJson;
//		}
	}
	
	/**
   	 * 用户登录界面
   	 * @throws Exception 
   	 */
    @RequestMapping("/logined") 
    public String logined(Operator form, Model model, HttpSession session){
		Operator operator = (Operator) session.getAttribute("Operator");
    	//菜单对象
		List<Menu> menulist = new ArrayList<Menu>();
		
		if("admin".equals(operator.getLoginname())){//超级管理员admin能查询到所有的菜单
			 
		}else{
			//
			Operatorroleref  operatorroleref = operatorrolerefDao.findByOperatorid(operator.getId());
			if(operatorroleref != null){
				Integer roleid = operatorroleref.getRoleid();
				List<Menu> list = menuDao.queryFirstMenuByRoleid(roleid);
				List<Integer> ids = new ArrayList<Integer>();
				for (Menu pid : list) {
					ids.add(pid.getPid());
				}
				menulist = menuDao.queryMenuByIds(ids);
				if (menulist != null && menulist.size() > 0) {
					for (Menu firstmenu : menulist) {
						Menu findsecondmenu = new Menu();
						findsecondmenu.setRoleid(roleid);
						findsecondmenu.setPid(firstmenu.getId());
						List<Menu> secondmenulist = menuDao.queryRelatedSecondMenu(findsecondmenu);
						firstmenu.setSecondmenulist(secondmenulist);
					}
				} else {
					// menu.setReturninfo("该用户没有权限!");
					System.out.println("该用户没有权限!");
				}
			}
			
			
		}
		
		model.addAttribute("menulist", menulist);
		model.addAttribute("operator", operator);
    	
        return "main"; 
    }
    
    
	/**
	 * 查询操作员信息
	 */
	@RequestMapping(value = "/findByList")
	public String findByList(Operator form) {
		return "operator/findOperatorList";
	}
	
	/**
	 * 查询用户信息Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findListJson")
	public Map<String, Object> findListJson(Operator form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
		
		Integer total = operatorService.findByCount(form);
		List<Operator> list = operatorService.findOperatorListForPage(form);
		
		for (Operator operator : list) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			
			objectMap.put("id", operator.getId());
			objectMap.put("loginname", operator.getLoginname());
			objectMap.put("addtime",  StringUtils.isEmpty(operator.getAddtime())?"":Tools.getStr(operator.getAddtime()).substring(0, 19));
			objectMap.put("status",  operator.getStatus());
			objectMap.put("sex", operator.getSex());
			objectMap.put("birthday", StringUtils.isEmpty(operator.getBirthday())?"":Tools.getStr(operator.getBirthday()).substring(0, 10));
			objectMap.put("identification", operator.getIdentification());
			objectMap.put("email", operator.getEmail());
			objectMap.put("address", operator.getAddress());
			objectMap.put("phone", operator.getPhone());
			objectMap.put("level", operator.getLevel());
			objectMap.put("status", operator.getStatus());
			objectMap.put("department", operator.getDepartment());
			
			//修改权限
			Operatorroleref orref = operatorrolerefDao.findByOperatorid(operator.getId());
			if(orref != null){
				Role role = roleDao.selectByPrimaryKey(orref.getRoleid());
				if(role != null){
					objectMap.put("rolecode", role.getRolecode());
					objectMap.put("rolename", role.getRolename());
				}
			}
			
			objectlist.add(objectMap);
		}
		
		result.put("code", "0");
		
		result.put("count", total);
		result.put("data", objectlist);
		return result;
	}

	/**
	 * 添加用户信息初始化
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addInit")
	public String addInit(Operator form,Model model) {
		model.addAttribute("rolelist", roleDao.findByList(new Role()));
		return "operator/addOperator";
	}

	/**
	 * 新增
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/save")
	@Transactional
	public Map<String,Object>  save(Operator form) {
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		if ("".equals(form.getLoginname())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，姓名不能为空");
			return responseJson;
		} else {
			Operator oldOperator = operatorService.findOperatorByLoginname(form);
			if (oldOperator != null) {
				responseJson.put("flag", "0");//添加失败
				responseJson.put("msg", "操作失败，姓名已经存在");
				return responseJson;
			}
		}
		
		//form.setStatus("在职");// 有效
		form.setAddtime(Tools.getCurrentTime());// 取当前时间
		operatorDao.insertSelective(form);
		
		Operatorroleref orref = new Operatorroleref();
		orref.setOperatorid(form.getId());
		orref.setRoleid(form.getRoleid());
		operatorrolerefDao.insertSelective(orref);
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}

	/**
	 * 更新初始化
	 */
	@RequestMapping(value = "/updateInit")
	public String updateInit(Operator form, Model model) {
		Operator operator = operatorService.selectByPrimaryKey(form.getId());
		
		Operatorroleref operatorroleref = operatorrolerefDao.findByOperatorid(form.getId());
		if(operatorroleref == null){
			operatorroleref = new Operatorroleref();
		}
		operator.setRoleid(operatorroleref.getRoleid());
		
		form.setOperator(operator);
		
		model.addAttribute("rolelist", roleDao.findByList(new Role()));
		
		return "operator/updateOperator";
	}

	/**
	 * 更新
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/update")
	@Transactional
	public Map<String,Object> update(Operator form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		if ("".equals(form.getLoginname())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，姓名不能为空");
			return responseJson;
		} else {
			Operator oldOperator = operatorService.findOperatorByLoginname(form);
			if (oldOperator != null && !oldOperator.getId().equals(form.getId())) {
				responseJson.put("flag", "0"); //添加失败
				responseJson.put("msg", "操作失败，登录名称已经存在");
				return responseJson;
			}
		}

		// 修改信息
		operatorService.updateByPrimaryKeySelective(form);
		
		//修改权限
		Operatorroleref orref = operatorrolerefDao.findByOperatorid(form.getId());
		orref.setOperatorid(form.getId());
		orref.setRoleid(form.getRoleid());
		operatorrolerefDao.updateByPrimaryKeySelective(orref);
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		return responseJson;
	}
    
	/**
	 * 删除操作员
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/delete")
	public Map<String,Object> delete(Operator form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		// 根据主键删除数据
		operatorService.deleteByPrimaryKey(form.getId());
		//删除操作员需要同时删除操作人人员对应的权限关系表
		operatorroleref.delByOperatorid(form.getId());


		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "删除成功");
		
		return responseJson;
	}
	
	/**
	 * 删除操作员
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/deleteBatch")
	public Map<String,Object> deleteBatch(@RequestBody List<Operator> formlist) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		for (Operator operator : formlist) {
			// 删除网络，实际上就是修改state为0-无效
			Operator operatordmp = operatorService.selectByPrimaryKey(operator.getId());
			operatordmp.setStatus("离职");
			operatorService.updateByPrimaryKeySelective(operatordmp);
		}

		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "删除成功");
		
		return responseJson;
	}
	
	/**
	 * 进入我的基本资料
	 */
	@RequestMapping(value = "/updateMyinfoInit")
	public String updateMyinfoInit(Operator form, HttpSession httpSession, HttpServletRequest request, Model model) throws UnsupportedEncodingException {
		Operator operator = (Operator) getSession().getAttribute("Operator");
		form.setOperator(operator);
		return "operator/updateMyinfo";
	}
	
	/**
	 * 更新
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/updateMyinfo")
	public Map<String,Object> updateMyinfo(Operator form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		if ("".equals(form.getLoginname())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，姓名不能为空");
			return responseJson;
		} else {
			Operator oldOperator = operatorService.findOperatorByLoginname(form);
			if (oldOperator != null && !oldOperator.getId().equals(form.getId())) {
				responseJson.put("flag", "0"); //添加失败
				responseJson.put("msg", "操作失败，登录名称已经存在");
				return responseJson;
			}
		}

		// 修改信息
		operatorService.updateByPrimaryKeySelective(form);
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		return responseJson;
	}
	
	/**
	 * 进入我的密码修改页面
	 */
	@RequestMapping(value = "/updateMypasswordInit")
	public String updateMypasswordInit(Operator form, HttpSession httpSession, HttpServletRequest request, Model model) throws UnsupportedEncodingException {
		Operator operator = (Operator) getSession().getAttribute("Operator");
		form.setOperator(operator);
		return "operator/updateMypassword";
	}
	
	/**
	 * 修改我的密码
	 * 
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/updateMypassword")
	public Map<String,Object> updateMypassword(Operator form) {

		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		Operator oldOperator = operatorService.selectByPrimaryKey(form.getId());
		//数据库的原密码
		String oldpassword = Tools.getStr(oldOperator.getPassword());
		//页面输入的原密码
		String oldpassword_input = Tools.getStr(getRequest().getParameter("oldPassword"));
		
		if (!oldpassword_input.equals(oldpassword)) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，原密码输入不正确");
			return responseJson;
		}

		operatorService.updateByPrimaryKeySelective(form);
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		return responseJson;
		
	}
	
}
